<template>
  <div>
    <!-- <div class="list-table" style="margin-bottom:20px;">
      <el-switch
        v-model="cashflowQuarterOrMonth"
        :active-text="$t('按月统计')"
        :inactive-text="$t('按季统计')"
      />
      <cashflow ref="cashflow" :quarter-or-month="cashflowQuarterOrMonth" />
    </div> -->
    <div class="list-table">
      <div class="area-header">
        <span class="area-header-title">{{ $t('现金流') }}</span>
      </div>
      <el-form ref="queryForm" :model="queryParams" :inline="true">
        <el-form-item :label="$t('项目名称')" prop="dealName">
          <el-input v-model="queryParams.dealName" />
        </el-form-item>
        <el-form-item :label="$t('现金流类型')" prop="type" label-width="120">
          <el-select v-model="queryParams.type" :placeholder="$t('现金流类型')" clearable>
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="$t(dict.dictLabel)"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('发生时间')" prop="operateDates">
          <DatePicker v-model="operateDates" type="daterange" />
        </el-form-item>
        <el-form-item :label="$t('方向')" prop="direction">
          <el-select v-model="queryParams.direction" :placeholder="$t('方向')" clearable>
            <el-option
              v-for="dict in directionOptions"
              :key="dict.dictValue"
              :label="$t(dict.dictLabel)"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('业务类型')" prop="operateType">
          <el-select v-model="queryParams.operateType" :placeholder="$t('业务类型')" clearable>
            <el-option
              v-for="dict in operateTypeOptions"
              :key="dict.dictValue"
              :label="$t(dict.dictLabel)"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t('搜索') }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['deal:cashflow:export']"
              type="warning"
              icon="el-icon-download"
              size="mini"
              @click="exportHandle"
            >{{ $t("导出") }}</el-button>
          </el-col>
        </el-col>
        <!--        <el-col :span="1.5">-->
        <!--          <el-button-->
        <!--            v-hasPermi="['deal:cashflow:view']"-->
        <!--            type="primary"-->
        <!--            icon="el-icon-info"-->
        <!--            size="mini"-->
        <!--            @click="getIrr"-->
        <!--          >{{ $t("获取IRR") }}</el-button>-->
        <!--        </el-col>-->
      </el-row>
      <el-table v-loading="loading" :data="dealCashflowList" border>
        <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
          <template slot-scope="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('项目名称')" align="center" prop="dealBase.dealName" min-width="200">
          <template slot-scope="scope">
            <span class="link-type" @click="updateHandle(scope.row)">{{ scope.row.dealBase.dealName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('现金流类型')"
          align="center"
          prop="type"
          :formatter="typeFormat"
          show-overflow-tooltip
          min-width="120"
        />
        <el-table-column
          :label="$t('业务类型')"
          align="center"
          prop="operateType"
          :formatter="operateTypeFormat"
          show-overflow-tooltip
          min-width="120"
        />
        <el-table-column :label="$t('权益变更时间')" align="center" prop="equityChangeTime" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.equityChangeTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('发生时间')" align="center" prop="operateDate" show-overflow-tooltip min-width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.operateDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('项目币种')" align="center" prop="currency" width="120">
          <template slot-scope="scope">
            <span>{{ formatCurrency(scope.row.currency) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('发生金额') + $t('(元)')" align="center" prop="operateAmount" width="120">
          <template slot-scope="scope">
            <span class="money-text">{{ moneyFormat(formatCurrencyMoney2(scope.row), undefined, 2, true) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('主体币种')" align="center" prop="currency" width="120">
          <template slot-scope="{}">
            <span>{{ formatCurrency(fundCurr) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('发生金额') + $t('(元)')" align="center" prop="operateAmount" width="120">
          <template slot-scope="scope">
            <span class="money-text">{{ moneyFormat(formatCurrencyMoney(scope.row), undefined, 2, true) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" min-width="100">
          <template slot="header">
            <span>{{ $t('操作') }}</span>
          </template>
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['deal:cashflow:edit']"
              size="small"
              type="text"
              :icon="'el-icon-edit'"
              @click="updateHandle(scope.row)"
            >{{ $t('修改') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改项目现金流对话框 -->
      <el-dialog
        :title="$t(title)"
        :visible.sync="formOpen"
        :close-on-click-modal="false"
        :lock-scroll="false"
        custom-class="dialogForm"
        append-to-body
      >
        <dealCashflowForm ref="dealCashflowForm" />
      </el-dialog>
    </div>
  </div>

</template>

<script>
import {
  listDealCashflow,
  delDealCashflow,
  getDealCashflowIrr,
  getCashFlowCombined,
  findDealCashFlowList
} from '@/api/deal/cashflow/dealCashflow'
import dealCashflowForm from '../cashflow/dealCashflowByFundForm.vue'
import { listDealInvestment } from '@/api/deal/investment/dealInvestment'
import { getFundBase } from '@/api/fund/fundBase'
import { getSystemCurrency } from '@/api/system/config'
// import cashflow from '@/views/chart/dealCashflow'
export default {
  components: {
    dealCashflowForm
    // cashflow
  },
  data() {
    return {
      isRate: false,
      fundCurr: '',
      defCurr: '',
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 项目现金流表格数据
      dealCashflowList: [],
      // 是否展示项目名称
      isShowDealName: false,
      // 弹出层标题
      title: '现金流',
      // 是否显示弹出层
      formOpen: false,
      // 现金流类型  预计 实际字典
      typeOptions: [],
      // 方向：流入、流出字典
      directionOptions: [],
      // 类型：投资、回款、费用字典
      operateTypeOptions: [],
      // 是否参与IRR计算字典
      whetherIrrOptions: [],
      // 当前项目投资主体
      investmentList: [],
      // 发生时间 参数
      operateDates: [],
      // 查询参数
      queryParams: {
        type: undefined,
        dealId: undefined,
        investorId: this.$route.query.id,
        dataId: undefined,
        component: undefined,
        startDate: undefined,
        endDate: undefined,
        direction: undefined,
        operateType: undefined,
        dealName: undefined,
        whetherIrr: 'Y',
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], dealId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], investorId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], operateDate: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], operateAmount: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], operateType: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ]
      },
      cashflowVO: {},
      cashflowQuarterOrMonth: false,
      currencyOptions: []
    }
  },
  computed: {},
  watch: {
    'queryParams.dealId': {
      handler(val) {
        this.investmentList = undefined
        listDealInvestment({ 'dealId': val }).then(response => {
          this.investmentList = response.rows
        })
      },
      immediate: true // 页面打开时就执行
    }
  },
  created() {
    this.initCurr()
    // 查询基金现金流合计信息
    this.getCashFlowCombined()
    this.getList()
    this.getDicts('cash_flow_type').then(response => {
      this.typeOptions = response.data
    })
    this.getDicts('cash_flow_direction').then(response => {
      this.directionOptions = response.data
    })
    this.getDicts('deal_cash_flow_type').then(response => {
      this.operateTypeOptions = response.data
    })
    this.getDicts('sys_yes_no').then(response => {
      this.whetherIrrOptions = response.data
    })
    this.getDicts('currency').then(response => {
      this.currencyOptions = response.data
    })
    /* listDealInvestment({ 'dealId': this.$route.query.id }).then(response => {
      this.investmentList = response.rows
    }) */
    // 根据项目ID是否为空 来显示项目名称
    this.isShowDealName = this.$route.query.id == null || this.$route.query.id === undefined
  },
  methods: {
    disbtn(val) {
      if (val) {
        return true
      } else {
        return false
      }
    },
    /** 查询项目现金流列表 */
    getList() {
      this.loading = true
      if (this.operateDates != null && this.operateDates.length > 1) {
        this.queryParams.startDate = this.operateDates[0]
        this.queryParams.endDate = this.operateDates[1]
      } else {
        this.queryParams.startDate = undefined
        this.queryParams.endDate = undefined
      }
      if (this.$route.name === 'fundBaseHome') {
        findDealCashFlowList(this.addDateRange(this.queryParams, this.operateDates)).then(response => {
          this.dealCashflowList = response.rows
          this.total = response.total
          this.loading = false
        })
      } else {
        listDealCashflow(this.addDateRange(this.queryParams, this.operateDates)).then(response => {
          this.dealCashflowList = response.rows
          this.total = response.total
          this.loading = false
        })
      }
    },
    // 现金流类型  预计 实际字典翻译
    typeFormat(row) {
      return this.selectDictLabel(this.typeOptions, row.type)
    },
    // 方向：流入、流出字典翻译
    directionFormat(row) {
      return this.selectDictLabel(this.directionOptions, row.direction)
    },
    // 类型：投资、回款、费用字典翻译
    operateTypeFormat(row) {
      return this.selectDictLabel(this.operateTypeOptions, row.operateType)
    },
    // 是否参与IRR计算字典翻译
    whetherIrrFormat(row) {
      return this.selectDictLabel(this.whetherIrrOptions, row.whetherIrr)
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        type: undefined,
        dealId: undefined,
        dataId: undefined,
        component: undefined,
        investorId: undefined,
        operateDate: undefined,
        operateAmount: undefined,
        direction: '0',
        operateType: undefined,
        whetherIrr: '0',
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.operateDates = []
      this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
      this.formOpen = true
      this.$nextTick(() => {
        this.$refs.dealCashflowForm.init(null)
      })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
      this.formOpen = true
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.dealCashflowForm.init(row)
      })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delDealCashflow(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    exportHandle() {
      this.downLoadExcelPost('/cashflow/dealCashflow/export', this.addDateRange(this.queryParams, this.operateDates))
    },
    // 计算irr
    getIrr() {
      getDealCashflowIrr(this.queryParams).then(res => {
        let msg = ''
        if (res.data === 502) {
          msg = this.$t('计算失败：小于或等于一条现金流')
        } else if (res.data === 503) {
          msg = this.$t('计算失败：第一条现金流的时间不是最早时间')
        } else if (res.data === 504) {
          msg = this.$t('计算失败：第一条现金流的payment的值不为负')
        } else {
          msg = res.data
        }
        this.$alert(msg, '当前数据IRR', {
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 初始化币种信息
    async initCurr(val) {
      let param = this.$route.query.id
      if (this.$route.query.id === undefined) {
        param = val
      }
      await getFundBase(param).then(res => {
        this.fundCurr = res.data.currency
      })
      await getSystemCurrency().then(res => {
        if (res.code === 200) {
          this.defCurr = res.data
        } else {
          this.msgError(res.msg)
        }
      })
      this.isRate = this.defCurr !== this.fundCurr
    },
    // 查询irr、dpi和moic
    getCashFlowCombined() {
      if (this.queryParams.investorId !== undefined) {
        getCashFlowCombined(this.queryParams.investorId).then(response => {
          this.cashflowVO = response.data
        })
      }
    },
    formatCurrency(val) {
      const currency = this.currencyOptions.find(obj => obj.dictValue === val)
      if (currency) {
        return currency.dictLabel
      }
      return val
    },
    formatCurrencyMoney(row) {
      if (row.operateAmountRMB) {
        if (row.direction === 'LC') {
          return 0 - row.operateAmountRMB
        } else {
          return row.operateAmountRMB
        }
      } else {
        return 0
      }
    },
    formatCurrencyMoney2(row) {
      if (row.operateAmount) {
        if (row.direction === 'LC') {
          return 0 - row.operateAmount
        } else {
          return row.operateAmount
        }
      } else {
        return 0
      }
    }
  }
}
</script>
